package cn.jd.basic.service.impl;

import cn.jd.basic.config.BussinessException;
import cn.jd.basic.constant.BaseConstants;
import cn.jd.basic.dto.AccountPhoneDto;
import cn.jd.basic.dto.LoginAccountDto;
import cn.jd.basic.dto.WXLoginDto;
import cn.jd.basic.dto.WechatLoginDto;
import cn.jd.basic.jwt.JwtUtils;
import cn.jd.basic.jwt.RsaUtils;
import cn.jd.basic.jwt.UserInfo;
import cn.jd.basic.service.LoginService;
import cn.jd.basic.util.AjaxResult;
import cn.jd.basic.util.HttpUtil;
import cn.jd.basic.util.MD5Utils;
import cn.jd.basic.util.StrUtils;
import cn.jd.system.domain.Menu;
import cn.jd.system.mapper.MenuMapper;
import cn.jd.system.mapper.PermissionMapper;
import cn.jd.user.domain.Logininfo;
import cn.jd.user.domain.User;
import cn.jd.user.domain.Wxuser;
import cn.jd.user.mapper.LogininfoMapper;
import cn.jd.user.mapper.UserMapper;
import cn.jd.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Value("${jwt.rsa.pri}")
    private String privateRsaKey;
    /**
     * 用户数据的保存
     */
    @Override
    public Map<String, Object> binder(WXLoginDto dto) {
        // 验证两次手机是否相同
        String redisSmsCode = (String)redisTemplate.opsForValue().get(String.format(BaseConstants.VerfityCodeCons.REGISTER_SMSCODE_PHONE, dto.getPhone()));
        if(StringUtils.isEmpty(redisSmsCode)){
            throw new BussinessException("两次账户不一致");
        }
        // 验证手机验证码是否正确
        if(dto.getSmsCode()==null){
            throw new BussinessException("验证码不能为空");
        }
        // 判断验证码是否正确
        if(dto.getSmsCode().equals(redisSmsCode)){
            throw new BussinessException("验证码错误");
        }
        // 调用微信的第三个接口获取用户数据
        String phone = dto.getPhone();
        String openid =(String) redisTemplate.opsForValue().get("openid");
        String access_token =(String) redisTemplate.opsForValue().get("access_token");
        String tokenUrl=String.format(BaseConstants.WxLoginCons.WX_USER_INFO,access_token,openid);
        String user = HttpUtil.httpGet(tokenUrl);
        Wxuser wxuser = JSONObject.parseObject(user, Wxuser.class);
        User byPhone = userMapper.findByPhone(phone);
        // 判断user表是否有该用户  有就直接添加wxuser表
        if(byPhone!=null){
            wxuser.setUserId(byPhone.getId());
            wxuserMapper.save(wxuser);
        }
        Logininfo logininfo = new Logininfo();
        logininfo.setPhone(phone);
        String password ="123456";
        logininfo.setUsername(phone);
        logininfo.setPassword(password);
        String salt = StrUtils.getComplexRandomString(32);
        String pass = MD5Utils.encrypByMd5(salt + password);
        logininfo.setSalt(salt);
        logininfo.setPassword(pass);
        logininfo.setType(1);
        logininfoMapper.save(logininfo);
        User user1 = new User();
        user1.setUsername(phone);
        user1.setPhone(phone);
        user1.setSalt(salt);
        user1.setPassword(pass);
        user1.setState(1);
        user1.setCreatetime(new Date());
        user1.setLogininfoId(logininfo.getId());
        userMapper.save(user1);
        wxuser.setUserId(user1.getId());
        wxuserMapper.save(wxuser);
        //使用UUId生成token的key
        String token = UUID.randomUUID().toString();
        // 将值存入到redis中
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //将私密信息隐藏
        logininfo.setPassword("");
        logininfo.setSalt("");
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }
    /**
     * 微信登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechatLogin(WechatLoginDto dto) {
        // 获取前端的code
        String code = dto.getCode();

        // 判断参数是否为空
        if (StringUtils.isEmpty(code)) {
            throw new BussinessException("code参数不能为空");
        }
        // 根据code获取appid
        String tokenUrl=String.format(BaseConstants.WxLoginCons.WX_ACCESS_TOKEN,
                BaseConstants.WxLoginCons.WX_APPID,BaseConstants.WxLoginCons.WX_SECRET,code);

        // 调用微信的第二。接口

        String s = HttpUtil.httpGet(tokenUrl);

        // 将json字符串转为json对象
        JSONObject jsonObject = JSONObject.parseObject(s);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        redisTemplate.opsForValue().set("openid",openid);
        redisTemplate.opsForValue().set("access_token",access_token);
        // 查询数据是否有openid
        Wxuser wxuser =wxuserMapper.finbyOpenId(openid);
        //判断微信user是否为空  不为空直接登录
        if(wxuser!=null&& wxuser.getUserId()!=null){
            // 查询logininfo的数据
            Logininfo  logininfo=logininfoMapper.findByUserId(wxuser.getUserId());


            //使用UUId生成token的key
            String token = UUID.randomUUID().toString();
            // 将数据存入到redis中
            redisTemplate.opsForValue().set(token, logininfo, 30, TimeUnit.MINUTES);
            // 5.将用户敏感信息置空
            logininfo.setPassword("");
            logininfo.setSalt("");
            // 6.并设置token和用户信息到map中
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("logininfo", logininfo);
            AjaxResult ajaxResult = AjaxResult.me().success().setResultObj(map);

            return  ajaxResult;
           }
       /* // 不存在告诉前端用户跳转到账号绑定页面，传递参数到前端，因为我们在下个接口需要使用
        StringBuffer sbr = new StringBuffer()
                .append("?accessToken=")
                .append(access_token)
                .append("&openId=").append(openid);*/
       /* return AjaxResult.me().setSuccess(false).setResultObj(sbr);*/
        return AjaxResult.me().setSuccess(false);

    }



    @Override
    public Map<String, Object> accountLogin(LoginAccountDto dto) {
        // 判断账户是否存在
        Logininfo logininfo=logininfoMapper.loadByTypeOrUsername(dto.getUsername(),dto.getType());
        if(logininfo==null){
            throw new BussinessException("账号或密码错误！！！");
        }
        //判断加研的密码是否一致
        System.out.println(logininfo.getSalt());
        String pas = MD5Utils.encrypByMd5( logininfo.getSalt()+dto.getPassword());
        if(!pas.equals(logininfo.getPassword())){
            throw new BussinessException("账号或密码错误！！！");
        }
        HashMap<String, Object> map = new HashMap<>();
        System.out.println(privateRsaKey+"++12++");
        //PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(privateRsaKey).getFile());
        // 创建UserInfo对象
        UserInfo user = new UserInfo();
        // 添加logininfo数据
        user.setLogininfo(logininfo);
        if(0==logininfo.getType()){
            // 2.1.获取用户权限信息，我们只需要sn权限编码即可
            List<String> permissions = permissionMapper.logininfoId(logininfo.getId());
            // 2.2.获取用户菜单信息
            List<Menu> menus = menuMapper.loadOwnMenuByLogininId(logininfo.getId());
            // 2.3.将菜单信息，权限信息放入到userinfo对象中
            user.setPermissions(permissions);
            user.setMenus(menus);
            map.put("permissions",permissions);
            map.put("menus",menus);
        }
        //根据密钥文件名称获取到密钥
        System.out.println(privateRsaKey);
//        PrivateKey privateKey = RsaUtils.getPrivateKey(this.getClass().getClassLoader().getResource(privateRsaKey).getFile());
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource(privateRsaKey).getFile());
       // 获取JWT加密串
        String token = JwtUtils.generateTokenExpireInMinutes(user, privateKey, 6000);
        //将私密信息隐藏
        logininfo.setPassword("");
        logininfo.setSalt("");
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }

    @Override
    public Map<String, Object> accountuser(AccountPhoneDto dto) {
        // 验证两次手机是否相同
        IfAuthCode(dto);
        Logininfo logininfo =logininfoMapper.loadByTypeOrUsername(dto.getUsername(),dto.getType());
        //使用UUId生成token的key
        String token = UUID.randomUUID().toString();
        // 将值存入到redis中
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //将私密信息隐藏
        logininfo.setPassword("");
        logininfo.setSalt("");
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        return map;
    }

    private void IfAuthCode(AccountPhoneDto dto) {
        String redisSmsCode = (String) redisTemplate.opsForValue().get(String.format(BaseConstants.VerfityCodeCons.REGISTER_SMSCODE_PHONE, dto.getUsername()));
        if(StringUtils.isEmpty(redisSmsCode)){
            throw new BussinessException("两次账户不一致");
        }
        // 验证手机验证码是否正确
        if(dto.getSmsCode()==null){
            throw new BussinessException("验证码不能为空");
        }
        // 判断验证码是否正确
        if(dto.getSmsCode().equals(redisSmsCode)){
            throw new BussinessException("验证码错误");
        }
    }


    public static void main(String[] args) {

        String p="15298240167";
        String d="31453971024083125714445171456084";
        String s = MD5Utils.encrypByMd5(d + p);
        System.out.println(s);

    }


}
